<template>
  <div class="address-list-container">
    <div class="header">
      <h2>地址管理</h2>
      <p class="subtitle">管理您的收货地址信息</p>
      <el-alert
          v-if="offlineMode"
          title="当前处于离线模式"
          type="warning"
          :closable="false"
          show-icon
          class="offline-alert"
      />
    </div>

    <div class="address-cards">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>

      <!-- 错误状态 -->
      <el-empty
          v-else-if="loadError"
          :description="errorMessage"
          :image-size="100"
      >
        <el-button type="primary" @click="retryFetch">重试</el-button>
      </el-empty>

      <!-- 正常状态 -->
      <template v-else>
        <el-card
            v-for="address in displayList"
            :key="address.id"
            class="address-card"
            shadow="hover"
            @click="selectAddress(address)"
        >
          <div class="address-content">
            <div class="user-info">
              <span class="name">{{ address.userName }}</span>
              <el-tag :type="address.gender === 1 ? 'primary' : 'danger'" size="small">
                {{ address.gender === 1 ? '先生' : '女士' }}
              </el-tag>
              <span class="phone">{{ address.phone }}</span>
            </div>
            <div class="address-detail">
              <el-icon><location /></el-icon>
              {{ address.address }}
              <el-tag v-if="address.localModified" type="warning" size="small" style="margin-left: 8px;">本地修改</el-tag>
            </div>
            <div v-if="address.isDefault" class="default-tag">
              <el-tag type="success" size="small">默认地址</el-tag>
            </div>
          </div>
          <div class="address-actions">
            <el-button
                type="primary"
                size="small"
                plain
                @click.stop="editAddress(address)"
            >
              <el-icon><edit /></el-icon> 编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                plain
                @click.stop="deleteAddress(address.id)"
            >
              <el-icon><delete /></el-icon> 删除
            </el-button>
          </div>
        </el-card>

        <el-empty
            v-if="displayList.length === 0"
            :description="offlineMode ? '暂无本地地址数据' : '暂无收货地址'"
            :image-size="100"
        />
      </template>
    </div>

    <div class="add-button">
      <el-button
          type="primary"
          round
          @click="addAddress"
          class="add-btn"
          plain
          :disabled="!canAddAddress"
      >
        <el-icon><plus /></el-icon>
        {{ offlineMode ? '新增本地地址' : '新增收货地址' }}
      </el-button>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑地址' : '新增地址'"
        width="90%"
        :style="{ maxWidth: '500px' }"
        :close-on-click-modal="false"
    >
      <el-form :model="addressForm" label-width="80px" ref="addressFormRef">
        <el-form-item label="收货人" prop="userName" :rules="formRules.userName">
          <el-input v-model="addressForm.userName" placeholder="请输入收货人姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="phone" :rules="formRules.phone">
          <el-input v-model="addressForm.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="地址" prop="address" :rules="formRules.address">
          <el-input
              v-model="addressForm.address"
              type="textarea"
              :rows="3"
              placeholder="请输入详细地址"
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addressForm.gender">
            <el-radio :value="1">男</el-radio>
            <el-radio :value="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
              type="primary"
              @click="submitAddress"
              :loading="submitting"
          >
            {{ offlineMode ? '本地保存' : '确认' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Location, Edit, Delete, Plus } from '@element-plus/icons-vue';

const router = useRouter();
const shipmentList = ref([]);
const localList = ref([]);
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentAddressId = ref(null);
const addressFormRef = ref(null);
const loading = ref(false);
const loadError = ref(false);
const errorMessage = ref('');
const offlineMode = ref(false);
const hasLocalStorage = ref(true);
const submitting = ref(false);

const canAddAddress = computed(() => {
  if (offlineMode.value && !hasLocalStorage.value) return false;
  if (loadError.value) return false;
  return true;
});

const displayList = computed(() => {
  if (offlineMode.value) {
    return localList.value;
  }
  return shipmentList.value.length > 0 ? shipmentList.value : localList.value;
});

const addressForm = ref({
  userName: '',
  phone: '',
  address: '',
  gender: 1,
  wechatId: '',
  isDefault: false
});

const formRules = {
  userName: [
    { required: true, message: '请输入收货人姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在2到10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入联系电话'));
        } else if (!/^1[3-9]\d{9}$/.test(value)) {
          if (offlineMode.value) {
            callback();
          } else {
            callback(new Error('请输入正确的手机号码'));
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, max: 100, message: '长度在5到100个字符', trigger: 'blur' }
  ]
};

// const checkNetworkStatus = async () => {
//   try {
//     if (!navigator.onLine) {
//       offlineMode.value = true;
//       return false;
//     }
//
//     offlineMode.value = !testResponse.ok;
//     return testResponse.ok;
//   } catch (error) {
//     offlineMode.value = true;
//     return false;
//   }
// };

const loadLocalData = () => {
  try {
    const localData = localStorage.getItem('addressList');
    if (localData) {
      localList.value = JSON.parse(localData);
    }
    hasLocalStorage.value = true;
  } catch (error) {
    console.error('读取本地存储失败:', error);
    hasLocalStorage.value = false;
    ElMessage.warning('本地存储不可用，数据将不会保存');
  }
};

const saveLocalData = (list) => {
  if (!hasLocalStorage.value) return;

  try {
    localStorage.setItem('addressList', JSON.stringify(list));
  } catch (error) {
    console.error('保存到本地存储失败:', error);
    hasLocalStorage.value = false;
  }
};

const fetchShipmentList = async () => {
  loadLocalData();
  const wechatId = localStorage.getItem('wechat_id');
  const token = localStorage.getItem('access_token');

  if (!wechatId || !token) {
    errorMessage.value = '用户信息缺失，请重新登录';
    loadError.value = true;
    return;
  }

  loading.value = true;
  loadError.value = false;

  try {
    const response = await fetch(`http://localhost:8080/shipment/list/${wechatId}`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error('获取收货地址失败');
    }

    shipmentList.value = await response.json();
    saveLocalData(shipmentList.value);
  } catch (error) {
    console.error('Error fetching shipment list:', error);
    errorMessage.value = '获取收货地址失败，已显示本地数据';
    loadError.value = true;
    loadLocalData();
  } finally {
    loading.value = false;
  }
};

const retryFetch = () => {
  fetchShipmentList();
};

const selectAddress = (address) => {
  ElMessage.success(`已选择地址: ${address.userName}`);
};

const addAddress = () => {
  isEdit.value = false;
  addressForm.value = {
    userName: '',
    phone: '',
    address: '',
    gender: 1,
    wechatId: localStorage.getItem('wechat_id') || '',
    isDefault: false
  };
  dialogVisible.value = true;
};

const editAddress = (address) => {
  isEdit.value = true;
  currentAddressId.value = address.id;
  addressForm.value = {
    userName: address.userName,
    phone: address.phone,
    address: address.address,
    gender: address.gender,
    wechatId: address.wechatId,
    isDefault: address.isDefault
  };
  dialogVisible.value = true;
};

const submitAddress = async () => {
  submitting.value = true;

  try {
    if (!offlineMode.value) {
      await addressFormRef.value.validate();
    }

    if (offlineMode.value) {
      const newAddress = {
        ...addressForm.value,
        id: isEdit.value ? currentAddressId.value : Date.now().toString(),
        localModified: true,
        syncStatus: 'pending'
      };

      if (isEdit.value) {
        const index = localList.value.findIndex(item => item.id === currentAddressId.value);
        if (index !== -1) {
          localList.value[index] = newAddress;
        }
      } else {
        localList.value.push(newAddress);
      }

      saveLocalData(localList.value);
      ElMessage.success('地址已本地保存，网络恢复后将自动同步');
    } else {
      const token = localStorage.getItem('access_token');
      const url = isEdit.value
          ? `http://localhost:8080/shipment/update`
          : `http://localhost:8080/shipment/insert`;
      const method = isEdit.value ? 'PUT' : 'POST';

      const body = isEdit.value
          ? { ...addressForm.value, id: currentAddressId.value }
          : addressForm.value;

      const response = await fetch(url, {
        method,
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(body)
      });

      if (!response.ok) {
        throw new Error(isEdit.value ? '更新地址失败' : '添加地址失败');
      }

      ElMessage.success(isEdit.value ? '地址更新成功' : '地址添加成功');
      await fetchShipmentList();
    }

    dialogVisible.value = false;
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('Error submitting address:', error);

      if (!offlineMode.value && error.message.includes('Failed to fetch')) {
        ElMessage.warning('网络异常，已转为本地保存');
        offlineMode.value = true;
        await submitAddress();
        return;
      }

      ElMessage.error(isEdit.value ? '更新地址失败' : '添加地址失败');
    }
  } finally {
    submitting.value = false;
  }
};

const deleteAddress = async (id) => {
  try {
    await ElMessageBox.confirm(
        offlineMode.value
            ? '当前处于离线模式，删除操作仅影响本地数据。确定要删除吗?'
            : '确定要删除该地址吗?',
        '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        });

    if (offlineMode.value) {
      localList.value = localList.value.filter(item => item.id !== id);
      saveLocalData(localList.value);
      ElMessage.success('地址已从本地删除');
      return;
    }

    const token = localStorage.getItem('access_token');
    const response = await fetch(`http://localhost:8080/shipment/delete/${id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    });

    if (!response.ok) {
      throw new Error('删除地址失败');
    }

    ElMessage.success('地址删除成功');
    await fetchShipmentList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Error deleting address:', error);
      ElMessage.error('删除地址失败');
    }
  }
};

onMounted(() => {
  loadLocalData();
  fetchShipmentList();

  window.addEventListener('online', () => {
    if (offlineMode.value) {
      ElMessage.info('网络已恢复，正在同步数据...');
      offlineMode.value = false;
      fetchShipmentList();
    }
  });

  window.addEventListener('offline', () => {
    offlineMode.value = true;
    ElMessage.warning('网络连接已断开，已切换到离线模式');
  });
});
</script>

<style scoped lang="scss">
.address-list-container {
  padding: 16px;
  max-width: 800px;
  margin: 0 auto;
  min-height: calc(100vh - 120px);
  position: relative;
  padding-bottom: 80px;

  .header {
    padding: 16px 0;
    text-align: center;
    margin-bottom: 20px;

    h2 {
      font-size: 24px;
      font-weight: 600;
      color: #333;
      margin-bottom: 8px;
    }

    .subtitle {
      font-size: 14px;
      color: #999;
      margin-bottom: 8px;
    }

    .offline-alert {
      margin: 0 auto 16px;
      max-width: 400px;
    }
  }

  .loading-container {
    padding: 20px;
  }

  .address-cards {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
    gap: 16px;
    margin-bottom: 20px;

    @media (max-width: 768px) {
      grid-template-columns: 1fr;
    }
  }

  .address-card {
    cursor: pointer;
    transition: all 0.3s ease;
    border-radius: 8px;
    position: relative;
    overflow: hidden;
    border: 1px solid #ebeef5;

    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .address-content {
      padding: 16px;

      .user-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;

        .name {
          font-weight: 600;
          font-size: 16px;
          color: #333;
        }

        .phone {
          color: #666;
          margin-left: auto;
          font-size: 14px;
        }
      }

      .address-detail {
        color: #666;
        line-height: 1.6;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 6px;
        flex-wrap: wrap;

        .el-icon {
          margin-top: 2px;
          color: var(--el-color-primary);
        }
      }

      .default-tag {
        position: absolute;
        top: 12px;
        right: 12px;
      }


    }

    .address-actions {
      display: flex;
      justify-content: flex-end;
      gap: 8px;
      padding: 12px;
      border-top: 1px solid #f0f0f0;
      background-color: #fafafa;
    }
  }

  .add-button {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    width: 100%;
    max-width: 800px;
    padding: 0 16px;
    z-index: 10;

    .add-btn {
      width: 100%;
      height: 48px;
      font-size: 16px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }

      .el-icon {
        margin-right: 6px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>